<template>
    <div class="app-container">
        <!-- 基站环境管理 -->
        <health-card :numLength="1" :overviewData="overviewData" class="env_health_card">
            <!-- 底部 -->
            <template #cardItem>
                <div class="card_item">
                    <overview-num-box :title="'隐患站点数量'">
                        <span>{{ overviewData.riskCount }}个</span>
                    </overview-num-box>
                </div>
                <div class="card_item">
                    <overview-box :title="'各区县基站环境平均分'">
                        <quxian :chart-data="overviewData.todayDistrictAverage" />
                    </overview-box>
                </div>
            </template>
        </health-card>

        <el-card shadow="always">
            <el-form :model="queryParams" :inline="true" label-width="100px">
                <el-form-item label="所属区县：" prop="county">
                    <el-select v-model="queryParams.county" placeholder="请选择所属区县" clearable style="width: 240px">
                        <el-option v-for="dict in nhp_county_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属站点ID" prop="stationId">
                    <el-input v-model="queryParams.stationId" placeholder="请输入站号" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="站点名称：" prop="siteName">
                    <el-input v-model="queryParams.stationName" placeholder="请输入基站名称" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="listEnvTable">查询</el-button>
                    <el-button @click="unsetQueryForm"><el-icon>
                            <RefreshRight />
                        </el-icon>重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="always" style="margin-top: 10px;min-height: 500px;padding-bottom: 3px;">
            <el-row>
                <el-button type="primary" icon="Upload" @click="uploadData">导入</el-button>
                <el-button type="primary" icon="Download" @click="exportData">导出</el-button>
            </el-row>
            <div id="table" style="margin-top: 20px;">
                <el-table v-loading="loading" ref="envTable" :data="tableData" style="width: 100%"
                    @sort-change="sortChange" @filter-change="filterChange">
                    <el-table-column prop="county" label="所属区县" width="120" align="center" fixed />
                    <el-table-column prop="stationId" label="所属站点ID" width="150" align="center" fixed />
                    <el-table-column prop="stationName" label="所属站点" width="350" align="center" fixed />
                    <el-table-column prop="createTime" label="创建日期" :formatter="dateFormatter" width="150"
                        align="center" />
                    <el-table-column prop="transmitType" label="传输是否成环" width="120" align="center"
                        :filter-multiple="false" :filters="[
                            { text: '成环', value: '成环' },
                            { text: '未成环', value: '未成环' },
                            { text: '未知', value: '未知' }
                        ]" :column-key="'transmitType'" />
                    <el-table-column prop="batteryDuration" label="蓄电池配置" width="150" align="center"
                        :filter-multiple="false" :filters="[
                            { text: '是', value: '是' },
                            { text: '否', value: '否' },
                        ]" :column-key="'batteryDuration'" filter-placement="bottom-end" />
                    <el-table-column prop="airconditionerStatus" label="空调状态" width="150" align="center"
                        :filter-multiple="false" :filters="[
                            { text: '正常', value: '正常' },
                            { text: '异常', value: '异常' },
                        ]" :column-key="'airconditionerStatus'" filter-placement="bottom-end" />
                    <el-table-column prop="inletRisk" label="台风进水风险" width="150" align="center" :filter-multiple="false"
                        :filters="[
                            { text: '是', value: '是' },
                            { text: '否', value: '否' },
                        ]" :column-key="'inletRisk'" filter-placement="bottom-end" />
                    <el-table-column prop="securityLevel" label="安全隐患" width="150" align="center"
                        :filter-multiple="false" :filters="[
                            { text: '是', value: '是' },
                            { text: '否', value: '否' },
                        ]" :column-key="'securityLevel'" filter-placement="bottom-end" />
                    <el-table-column prop="electricGeneration" label="发电条件" width="150" align="center"
                        :filter-multiple="false" :filters="[
                            { text: '是', value: '是' },
                            { text: '否', value: '否' },
                        ]" :column-key="'electricGeneration'" filter-placement="bottom-end" />
                    <el-table-column prop="lyStation" label="是否拉远" width="150" align="center" :filter-multiple="false"
                        :filters="[
                            { text: '拉远', value: '拉远' },
                            { text: '非拉远', value: '非拉远' },
                        ]" :column-key="'electricGeneration'" filter-placement="bottom-end" />
                    <el-table-column prop="score" label="环境告警总分" width="150" align="center" fixed="right"
                        sortable="custom" />
                    <el-table-column fixed="right" label="操作" align="center">
                        <template #default="scope">
                            <el-button link type="primary" size="small"
                                @click="showDetailDialog(scope.row.stationId)">修改</el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty :image-size="40" />
                    </template>
                </el-table>
                <!-- <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next" :total="total" @size-change="listEnvTable"
                    @current-change="listEnvTable" /> -->
                <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
                    @pagination="listAlarmTable" :autoScroll="false" />
            </div>
        </el-card>

        <el-dialog v-model="detailDialogVisible" title="修改基站环境信息" width="1000" @closed="closeDialog">
            <el-form :inline="true" :model="envForm" label-width="200px">
                <el-form-item label="所属区县">
                    <el-input v-model="envForm.county" disabled style="width: 200px" />
                </el-form-item>
                <el-form-item label="所属站点ID">
                    <el-input v-model="envForm.stationId" disabled style="width: 200px" />
                </el-form-item>
                <el-form-item label="所属站点">
                    <el-input v-model="envForm.stationName" disabled style="width: 200px" />
                </el-form-item>
                <el-form-item label="是否拉远">
                    <el-input v-model="envForm.lyStation" disabled style="width: 200px" />
                </el-form-item>
                <el-form-item label="传输是否成环">
                    <el-input v-model="envForm.transmitType" disabled style="width: 200px" />
                </el-form-item>
                <el-form-item label="蓄电池配置">
                    <el-select v-model="envForm.batteryDuration" disabled style="width: 200px">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="空调状态">
                    <el-select v-model="envForm.airconditionerStatus" style="width: 200px">
                        <el-option v-for="item in airOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="台风进水风险">
                    <el-select v-model="envForm.inletRisk" style="width: 200px">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="安全隐患">
                    <el-select v-model="envForm.securityLevel" style="width: 200px">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="发电条件">
                    <el-select v-model="envForm.electricGeneration" style="width: 200px">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="updateEnv">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <export-dialog ref="refExportDialog" @directExport="directExportData" />
        <el-dialog v-model="uplaodDialogVisible" title="导入基站环境数据" width="500" @closed="closeDialog">
            <el-form label-width="120px">
                <el-form-item label="文件上传">
                    <el-upload :action="uploadFileUrl" class="upload-demo" :headers="headers" :show-file-list="false"
                        :on-success="uploadSuccess">
                        <el-button type="primary">上传</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item label="模版下载">
                    <a @click="downloadTemplate" class="download-link">基站环境导入模版.xlsx</a>
                </el-form-item>
            </el-form>

        </el-dialog>
    </div>
</template>

<script setup name="networkEnv">
import { queryByPage, queryById, updateStationEnv, calculateEnvScore, queryEnvOverview } from '@/api/biz/networkEnv';

import { useConfigStore } from "@/store/modules/config.js";

import qushi from "../chart/qushi.vue";
import { ref } from 'vue';
import { ElMessage } from 'element-plus'
import quxian from "../chart/quxian.vue";
import { getToken } from "@/utils/auth";


let overviewData = ref({})

const { proxy } = getCurrentInstance();

var currentDate = new Date();
currentDate.setDate(currentDate.getDate() + 1);

const refExportDialog = ref(null)

let loading = ref(false)

const configStoreData = useConfigStore();
let securityFlagConfig = configStoreData.configList.filter(
    (item) => item.configKey === "sys.securityFlag"
)[0];
// console.log("securityFlagConfig", securityFlagConfig);

const { nhp_county_type } = proxy.useDict("nhp_county_type");

const queryParams = ref({
    county: "",
    stationId: "",
    stationName: "",
    exportType: '环境维度导出'
})
// console.log(queryParams.value)

const tableData = ref([])
const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)

const detailDialogVisible = ref(false)
const envForm = ref({})
const nowOrder = ref();
const dataTime = ref(null);
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + '/nhpStationEnv/importStationEnv');
const headers = ref({ Authorization: "Bearer " + getToken() });

const options = [
    {
        key: "是",
        value: "是"
    },
    {
        key: "否",
        value: "否"
    },
]

const airOptions = [
    {
        key: "正常",
        value: "正常"
    },
    {
        key: "异常",
        value: "异常"
    }
]


const uplaodDialogVisible = ref(false)

const setTodayDistrictAverageSort = () => {
    let topThree = overviewData.value.todayDistrictAverage.map((item, index) => ({ ...item, index })).sort((a, b) => b.value - a.value).slice(0, 3)
    let lastThree = overviewData.value.todayDistrictAverage.map((item, index) => ({ ...item, index })).sort((a, b) => b.value - a.value).slice(-3)

    overviewData.value.todayDistrictAverage.push({
        topThree, lastThree,
    })
    // console.log(overviewData.value.todayDistrictAverage)

    topThree.forEach((item, index) => {
        overviewData.value.todayDistrictAverage[item.index].itemStyle = {
            color: '#92cc76'
        }
    })
    lastThree.forEach(item => {
        overviewData.value.todayDistrictAverage[item.index].itemStyle = {
            color: '#a90000'
        }
    })
}


const dataOverview = () => {

    queryEnvOverview().then(res => {
        let data = res.data
        let todayDistrictAverage = []
        for (let i = 0; i < data.countyList.length; i++) {
            todayDistrictAverage.push({
                name: data.countyList[i],
                value: data.countyAvgScoreList[i]
            })
        }
        overviewData.value = {
            todayAverage: data.avgScore,
            riskCount: data.riskCount,
            todayDistrictAverage: todayDistrictAverage,
        }

        dataTime.value = data.dateTime
        listEnvTable();
        setTodayDistrictAverageSort()

    })
}
dataOverview()

function listEnvTable() {
    const param = {}
    param.pageSize = pageSize.value
    param.pageNum = currentPage.value
    param.stationId = queryParams.value.stationId
    param.county = queryParams.value.county
    param.stationName = queryParams.value.stationName
    param.order = nowOrder.value;
    param.createTime = formatDate(dataTime.value)
    loading.value = true
    queryByPage(param).then(response => {
        loading.value = false;
        tableData.value = response.rows;
        total.value = response.total;
    });
}

function unsetQueryForm() {
    queryParams.value = {
    }
}

function uploadData() {
    uplaodDialogVisible.value = true
}


//导出
function exportData() {
    const param = {}
    param.stationId = queryParams.value.stationId
    param.county = queryParams.value.county
    param.stationName = queryParams.value.stationName
    param.createTime = formatDate(dataTime.value)

    if (securityFlagConfig.configValue == "true") {
        //开启金库模式
        refExportDialog.value.show(param);
    } else {
        proxy.download("/nhpStationEnv/export", {
            ...param
        }, `基站环境_${new Date().getTime()}.xlsx`);
    }
}

function directExportData() {
    const param = {}
    param.pageSize = pageSize.value
    param.pageNum = currentPage.value
    param.stationId = queryParams.value.stationId
    param.county = queryParams.value.county
    param.stationName = queryParams.value.stationName
    param.order = nowOrder.value;
    proxy.download("/nhpStationEnv/exportDirectEnv", {
        ...param
    }, `基站环境(剔除敏感数据)_${new Date().getTime()}.xlsx`);
}

//修改
function showDetailDialog(stationId) {
    detailDialogVisible.value = true
    let param = {
        stationId: stationId,
        createTime: formatDate(dataTime.value)
    }
    queryById(param).then(response => {
        envForm.value = response.data
    })
}

function closeDialog() {
    envForm.value = {}
}

function updateEnv() {
    var param = {}
    param.stationId = envForm.value.stationId
    param.batteryDuration = envForm.value.batteryDuration
    param.airconditionerStatus = envForm.value.airconditionerStatus
    param.inletRisk = envForm.value.inletRisk
    param.securityLevel = envForm.value.securityLevel
    param.electricGeneration = envForm.value.electricGeneration
    param.createTime = formatDate(dataTime.value)
    updateStationEnv(param).then(response => {
        detailDialogVisible.value = false
        ElMessage({
            message: '修改成功',
            type: 'success',
            plain: true,
        })
        listEnvTable()
    })
}

function calculateScore() {
    calculateEnvScore().then(response => {
        ElMessage({
            message: '开始计算',
            type: 'success',
            plain: true,
        })
    })
}

// 总分排序
function sortChange(column, prop, order) {
    nowOrder.value = column.order;
    listEnvTable();
}


// 筛选状态
function filterChange(filters) {
    const param = {}
    if (filters.hasOwnProperty("transmitType")) {
        param.transmitType = filters.transmitType[0]
    }
    if (filters.hasOwnProperty("batteryDuration")) {
        param.batteryDuration = filters.batteryDuration[0]
    }
    if (filters.hasOwnProperty("airconditionerStatus")) {
        param.airconditionerStatus = filters.airconditionerStatus[0]
    }
    if (filters.hasOwnProperty("inletRisk")) {
        param.inletRisk = filters.inletRisk[0]
    }
    if (filters.hasOwnProperty("securityLevel")) {
        param.securityLevel = filters.securityLevel[0]
    }
    if (filters.hasOwnProperty("electricGeneration")) {
        param.electricGeneration = filters.electricGeneration[0]
    }


    param.pageSize = pageSize.value
    param.pageNum = currentPage.value
    param.stationId = queryParams.value.stationId
    param.county = queryParams.value.county
    param.stationName = queryParams.value.stationName
    param.order = nowOrder.value;
    queryByPage(param).then(response => {
        tableData.value = response.rows;
        total.value = response.total;
    });
}

function dateFormatter(row, column, cellValue, index) {
    if (!cellValue) { return }
    // 创建一个新的 Date 对象
    var originalDate = new Date(cellValue);

    // 获取年、月、日、时、分、秒
    var year = originalDate.getFullYear();
    var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
    var day = ("0" + originalDate.getDate()).slice(-2);
    var hours = ("0" + originalDate.getHours()).slice(-2);
    var minutes = ("0" + originalDate.getMinutes()).slice(-2);
    var seconds = ("0" + originalDate.getSeconds()).slice(-2);

    // 格式化输出
    var formattedDateTimeString = year + "-" + month + "-" + day;
    return formattedDateTimeString;
}

function formatDate(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 加 1 因为月份是从 0 开始的，并使用 padStart 来确保月份是两位数  
    const day = date.getDate().toString().padStart(2, '0'); // 使用 padStart 来确保日期是两位数  
    return `${year}-${month}-${day}`;
}

function downloadTemplate() {
    proxy.download("/export/downloadTemplate", {
        templateName: "基站环境导入模版.xlsx"
    }, `基站环境导入模版.xlsx`);
}

function uploadSuccess(res, file, fileList) {
    uplaodDialogVisible.value = false
    ElMessage.success(res.msg)
}

</script>

<style>
.download-link {
    display: block;
    padding: 5px 10px;
    color: #007bff;

    text-decoration: none;
    border-radius: 4px;
}

.el-form-item a {
    display: inline-block;
    /* 确保链接被视为块级元素的一部分，便于调整 */
    vertical-align: middle;
    text-decoration: underline;
}
</style>
